<template>
    <div class="editType" ref="editType" >
        <el-dialog width="80%" @close="dialogClose" :visible="visible">
            <div class="table—nav">
                <div class="first" :style="curStyle('first', curLength>0, activeName)">第一步：添加商品类型</div>
                <div class="scond" :style="curStyle('second', curLength>1,activeName)">第二步：添加扩展属性</div>
                <div class="third" :style="curStyle('third', curLength>2,activeName)">第三步：添加规格</div>
            </div>
            <div class="first-child" v-if="activeName === 'first'">
                <el-form
                    v-if="editForm"
                    ref="form" 
                    :model="editForm" 
                    label-width="120px"
                    :rules="rules"
                >
                    <el-form-item label="商品类型名称:" prop="name">
                        <el-input v-model="editForm.name" style="width: 400px;"></el-input>
                    </el-form-item>

                    <el-form-item label="备注">
                        <el-input type="textarea" v-model="editForm.remark" style="width: 400px;"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">下一步</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="second-child" v-else-if="activeName === 'second'">
                <el-table
                        :data="expandData"
                        style="width: 100%">
                        <el-table-column
                            prop="name"
                            label="属性名称"
                            width="220">
                            <template slot-scope="scope">
                                <el-input type="text" v-model="scope.row.name" style="width: 100px;margin-right:10px;"></el-input>
                                <el-button type="success" icon="el-icon-edit" size="mini" @click="editName(scope.$index)">修改</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="value"
                            label="支持多选"
                            width="80"
                            >
                            <template slot-scope="scope">
                                <span 
                                    @click="changeSeq(scope.$index, scope.row.displaySeq)"
                                    :class="scope.row.displaySeq ? 'el-icon-check' : 'el-icon-close'" 
                                    :style="{cursor: 'pointer',color: scope.row.displaySeq ? '#0d97eb' : '#f00'}">
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="address"
                            width="auto"
                            label="属性值">
                            <template slot-scope="scope">
                                <el-tag
                                    :key="index"
                                    v-for="(tag, index) in scope.row.valueList"
                                    closable
                                    :disable-transitions="false"
                                    @close="handleClose(index, scope.row.valueList)">
                                    {{tag.valueStr}}
                                </el-tag>

                                <el-input
                                    class="input-new-tag"
                                    v-if="inputVisible && scope.$index === curIndex"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope)"
                                    @blur="handleInputConfirm(scope)"
                                    >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.$index)">+ 添加属性值</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column
                            width="50"
                            prop="address"
                            label="排序">
                        </el-table-column>
                        <el-table-column
                            label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="success" @click="handeEditAttrs(scope.row)" class="el-icon-edit">编辑</el-button>
                                <el-button size="mini" type="success" class="el-icon-delete" @click="handeDelAttr(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <span v-html="tableStyle"></span>
                    <el-button type="primary" @click="addType">添加扩展属性</el-button>
                    <el-button type="primary" @click="next">下一步</el-button>
            </div>
            <div class="third-child" v-else>
                <el-table
                    :data="specsData"
                    style="width: 100%">
                    <el-table-column
                        prop="name"
                        label="规格名称"
                        width="220">
                        <template slot-scope="scope">
                            <el-input type="text" v-model="scope.row.name" style="width: 100px;margin-right:10px;"></el-input>
                            <el-button type="success" icon="el-icon-edit" size="mini" @click="editSpecsName(scope.$index)">修改</el-button>
                        </template>
                    </el-table-column>
                    
                    <el-table-column
                            prop="value"
                            label="可上传规格图"
                            width="80"
                            >
                            <template slot-scope="scope">
                                <span 
                                    @click="changeSeq(scope.$index, scope.row.displaySeq ,true)"
                                    :class="scope.row.displaySeq ? 'el-icon-check' : 'el-icon-close'" 
                                    :style="{cursor: 'pointer',color: scope.row.displaySeq ? '#0d97eb' : '#f00'}">
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="address"
                            width="auto"
                            label="规格值">
                            <template slot-scope="scope">
                                <el-tag
                                    :key="index"
                                    v-for="(tag, index) in scope.row.valueList"
                                    closable
                                    :disable-transitions="false"
                                    @close="handleClose(index, scope.row.valueList)">
                                    {{tag.valueStr}}
                                </el-tag>

                                <el-input
                                    class="input-new-tag"
                                    v-if="inputVisible && scope.$index === curIndex"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope)"
                                    @blur="handleInputConfirm(scope)"
                                    >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.$index)">+ 添加属性值</el-button>
                            </template>
                        </el-table-column>
                    <el-table-column
                        width="50"
                        prop="address"
                        label="排序">
                    </el-table-column>
                    <el-table-column
                        label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" type="success" @click="handeEditSpces(scope.row)" class="el-icon-edit">编辑</el-button>
                            <el-button size="mini" type="success" class="el-icon-delete" @click="handeDelAttr(scope.row.id, true)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <span v-html="tableStyle"></span>
                <el-button type="primary" @click="handeaddSpces">添加规格</el-button>
                <el-button type="primary" @click="dialogClose">完成</el-button>
            </div>
        </el-dialog>
        <!-- 添加扩展属性 -->
        <add-expand-type
            :addExTy="addExTy"
            :id="editForm.id"
            :typeId="editForm.typeId"
            @cancel="cancel"
        >
        </add-expand-type>

        <!-- 添加规格 -->
        <add-spces-dialog
            :addSpcesDialog="addSpcesDialog"
            :id="editForm.id"
            :typeId="editForm.typeId"
            @cancelSpces="cancelSpces"
        >
        </add-spces-dialog>

        <!-- 编辑当前扩展属性 -->
        <edit-attrs-dialog
            :showAttrDialog="showAttrDialog"
            :typeId="editForm.id"
            :attrs="curAttrs"
            @cancel="cancel"
            @success="success"
        >
        </edit-attrs-dialog>
        <!-- 编辑当前规格 -->
        <edit-specs-dialog
            :showSpecsDialog="showSpecsDialog"
            :typeId="editForm.id"
            :attrs="curAttrs"
            @cancelSpces="cancelSpces"
            @success="success"
        >
        </edit-specs-dialog>
    </div>
</template>

<script>
import {
    editProType,
    expandType,
    specs,
    addExpandAttr,
    addSpces,
    delExpandAttr,
    delExpandAttrValue,
    addExpandAttrValue
} from "@/api/agri-product/goodsType"
import AddExpandType from './addExpandType'
import EditAttrsDialog from './editAttrsDialog'
import EditSpecsDialog from './editSpecsDialog'
import AddSpcesDialog from './addSpcesDialog'
export default {
    name: 'productTypeEditDL',
    components: {
        AddExpandType,
        EditAttrsDialog,
        EditSpecsDialog,
        AddSpcesDialog
    },
    data () {
        return {
            editForm: {},
            curIndex: '',
            curLength: 0,
            curAttrs: [],
            curSpecs: [],
            inputVisible: false,
            inputValue: '',
            addExTy: false,
            showAttrDialog: false,
            showSpecsDialog: false,
            addSpcesDialog: false,
            activeName: 'first', //当前选择
            DialogVisible: true,
            rules: {
                name :[{required: true, message: '请输入商品类型名称', trigger: 'blur'}]
            },
            expandData: [],
            specsData: []
        }
    },
    props: ['visible', 'newData'],
    created () {
        console.log(this.editForm, this.visible, '11111')
    },
    computed: {
        tableStyle () {
            return `
                <style>
                    .addtable .el-tabs__nav {
                        width: 100% !important;
                        display: flex;
                        justify-content: space-between;
                    }
                    .addtable .el-tabs__active-bar {
                        display: none !important;
                    }
                    .addtable #tab-second, .addtable #tab-first, .addtable #tab-third{
                        width: 30% !important;
                        padding: 0 !important;
                        text-align: center !important;
                        background: red;
                    }
                    .el-table .cell {
                        white-space: pre-wrap !important;
                    }
                    .el-table .el-tabs__nav-wrap:after {
                        height: 0 !important;
                    }
                </style>
            `
        }
    },
    methods: {
        handleClick(tab, event) {
            console.log(tab, event);
        },
        //关闭弹窗
        dialogClose () {
            this.$emit("cancel");
        },
        // 基本属性-保存
        onSubmit () {
            this.$refs['form'].validate((valid) => {
                if (!valid) return false;

                editProType(this.editForm).then(res => {
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    });
                    this.activeName = 'second';
                    this.$emit('loadData', {
                        pageSize: 10,
                        currentPage: 1,
                        total: 0
                    }, {}, true)
                }).catch(err => {
                    this.$message({
                        type: 'info',
                        message: '添加失败'
                    });
                })
            });
            
        },
        //扩展属性列表
        productAttr () {
            expandType(this.editForm.id).then(res => {
                this.expandData = res.data.data.records;
                this.expandData.forEach(item => {
                    item.value = item.value ? item.value.replace(/，/g, ',').split(',') : [];
                })
            })
        },
        // 扩展属性-添加属性按钮
        addType () {
            this.addExTy = true;
        },
        handeaddSpces () {
            this.addSpcesDialog = true;
        },
        // 扩展属性-关闭弹窗
        cancel (status) {
            this.addExTy = false;
            this.showAttrDialog = false;
            status && this.productAttr() 
        },
        // 规格-关闭弹窗 
        cancelSpces (status) {
            this.showSpecsDialog = false;
            this.addSpcesDialog = false;
            status && this.skuItem() 
        },

        // 扩展属性-删除属性值
        handleClose (index, item, isSku) {
            delExpandAttrValue(item[index].id).then(res => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                isSku ? this.skuItem() : this.productAttr();
            }).catch(err => {
                this.$message({
                    type: 'info',
                    message: '删除失败'
                });
            })
        },
        // 规格-删除规格值
        handleSpecsClose (scope, index) {
            let newObj = JSON.parse(JSON.stringify(this.specsData[scope.$index]));
            newObj.value.splice(index, 1);
            newObj.value = newObj.value.join(',');
            addSpces(newObj).then(res => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.skuItem()
            }).catch(err => {
                this.$message({
                    type: 'info',
                    message: '删除失败'
                });
            })
        },
        //扩展属性-设置支持多选状态
        changeSeq (index, status, isSku) {
            let newObj = isSku ? this.specsData[index] : this.expandData[index];
            newObj.displaySeq = !status;
            let data = {}
            data.name = newObj.name;
            data.typeId = newObj.typeId;
            data.id = newObj.id;
            data.displaySeq = newObj.displaySeq ? 1 : 0;
            addExpandAttr(data).then(res => {
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });
                isSku ? this.skuItem() : this.productAttr()
            }).catch(err => {
                this.$message({
                    type: 'info',
                    message: '修改失败'
                });
            })
        },
        // 修改扩展属性名称
        editName (index) {
            let newObj = JSON.parse(JSON.stringify(this.expandData[index]));
            if (newObj.name.trim().length === 0) {
                this.$message({
                    type: 'info',
                    message: '修改失败,属性名称不能为空'
                });
                return;
            }
            let data = {}
            data.name = newObj.name;
            data.displaySeq = newObj.displaySeq;
            data.typeId = newObj.typeId;
            data.id = newObj.id;
            addExpandAttr(data).then(res => {
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });
                this.productAttr()
            }).catch(err => {
                this.$message({
                    type: 'info',
                    message: '修改失败'
                });
            })
        },
        // 修改规格名称
        editSpecsName (index) {
            let newObj = JSON.parse(JSON.stringify(this.specsData[index]));
            if (newObj.name.trim().length === 0) {
                this.$message({
                    type: 'info',
                    message: '修改失败,属性名称不能为空'
                });
                return;
            }
            newObj.value = newObj.value.join(',');
            addSpces(newObj).then(res => {
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });
                this.skuItem()
            }).catch(err => {
                this.$message({
                    type: 'info',
                    message: '修改失败'
                });
            })
        },
        // 扩展属性-添加属性值
        showInput(index) {
            this.curIndex = index;
            this.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        // 扩展属性-添加属性值 
        showSpcesInput(index) {
            this.curIndex = index;
            this.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        // 扩展属性-规格-删除当前扩展属性
        handeDelAttr (id, type) {
            delExpandAttr(id).then(res =>{
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                type ? this.skuItem() : this.productAttr()
            }).catch(err => {
                this.$message({
                    type: 'info',
                    message: '删除失败'
                });
            })
        },
        // 扩展属性-添加属性值
        handleInputConfirm(scope, isSku) {
            let inputValue = scope.row.inputValue;
            if (inputValue) {
                let data = {};
                console.log(scope, '111111233344')
                data.attrId = scope.row.id;
                data.displaySeq = scope.row.displaySeq ? 1 : 0;
                data.imageUrl = scope.row.imageUrl;
                data.valueStr = scope.row.inputValue;
                addExpandAttrValue(data).then(res => {
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    });
                    isSku ? this.skuItem() : this.productAttr()
                }).catch(err => {
                    this.$message({
                        type: 'info',
                        message: '添加失败失败'
                    });
                })
                
            }
            this.inputVisible = false;
            scope.row.inputValue = '';
        },
        // 规格-添加属性值
        handleSpecsInputConfirm(scope) {
            let inputValue = scope.row.inputValue;
            if (inputValue) {
                let newObj = JSON.parse(JSON.stringify(this.specsData[scope.$index]));
                // console.log()
                newObj.value.push(inputValue);
                newObj.value = newObj.value.join(',');
                newObj.displaySeq = newObj.displaySeq ? 1 : 0;
                addSpces(newObj).then(res => {
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    });
                    this.skuItem()
                }).catch(err => {
                    this.$message({
                        type: 'info',
                        message: '添加失败失败'
                    });
                })
                
            }
            this.inputVisible = false;
            scope.row.inputValue = '';
        },
        // 扩展属性-编辑当前属性
        handeEditAttrs (value) {
            this.curAttrs = value;
            this.showAttrDialog = true;
        },
        // 规格-编辑当前规格
        handeEditSpces (value) {
            this.curAttrs = value;
            this.showSpecsDialog = true;
        },
        // 规格列表
        skuItem () {
             specs(this.editForm.id).then(res => {
                this.specsData = res.data.data.records;
                this.specsData.forEach(item => {
                    item.value = item.value ? item.value.replace(/，/g, ',').split(',') : [];
                })
            })
        },
        curStyle (type, status) {
            if (status) {
                return 'background: #ff9979; color: #fff;'
            }
            console.log(this.activeName === type, status)
            return this.activeName === type ? 'background: #ff551f; color: #fff;' : 'background: #ebebeb; color: #333;'
        },
        next () {
            this.activeName = 'third'
            this.$emit('loadData', {
                        pageSize: 10,
                        currentPage: 1,
                        total: 0
                    }, {}, true)
        },
        success (isSku) {
            isSku ? this.skuItem() : this.productAttr();
            this.showAttrDialog = false;
            this.showSpecsDialog = false;
        }
    },
    watch: {
        activeName (cur) {
            cur === 'second' && (this.curLength = 1)
            cur === 'third' && (this.curLength = 2)
        },
        newData (cur) {
            this.editForm = cur;
        },
        visible () {
            this.activeName = 'first',
            this.expandData = [];
            this.specsData = [];
            this.curLength = 0;
        }
    }
}
</script>

<style scoped>
.table tr td .cell {
    overflow-x: scroll !important;
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .table—nav {
    display: flex;
    width: 100%;
    height: 40px;
    line-height: 40px;
    justify-content: space-between;
    margin-bottom: 30px;
  }
  .table—nav>div {
      text-align: center;
      background: #ebebeb;
      color: #333;
      width: 30%;
  }
  .curStyle {
      background: #ff551f;
       color: #fff;
  }
  .afterStyle {
      background: #ebebeb;
       color: #333;
  }
</style>